package com.pioneer.swing.controller;

import com.pioneer.dao.*;
import com.pioneer.beans.*;
import com.pioneer.dao.DataAccessException;
import com.pioneer.swing.ui.*;
import com.pioneer.swing.model.*;

import java.util.Arrays;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.JInternalFrame;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.TableModel;
import javax.swing.JDialog;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import java.util.List;
import java.text.NumberFormat;
import java.text.DecimalFormat;

/**
 * Title:        Pioneer Metals
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:      Pioneer Metals
 * @author Gary Chen
 * @version 1.0
 */

public class WindowRefresher extends InternalFrameAdapter
implements ActionListener{
	
	private final String NA_STRING = " Not Available";

	private ManifestDAO manifestDAO;
	private JobDAO jobDAO;
	private ContactDAO contactDAO;
	private JDesktopPane desktopPane;

    public WindowRefresher(JDesktopPane desktopPane) {		
		this.desktopPane = desktopPane;
    }
	
	public void setManifestDAO(ManifestDAO manifestDAO) {
		this.manifestDAO=manifestDAO;
	}
	
	public void setContactDAO(ContactDAO contactDAO) {
		this.contactDAO = contactDAO;
	}
	
	public void setJobDAO(JobDAO jobDAO) {
		this.jobDAO = jobDAO;
	}
	
    public static void main(String[] args) {
        //WindowRefresher windowCloser1 = new WindowRefresher();
    }

	public void internalFrameActivated(InternalFrameEvent e) {
		
		
		JInternalFrame internalFrame=e.getInternalFrame();
		int clickedLayer = internalFrame.getLayer();
		int highestLayer = desktopPane.highestLayer();
		if (clickedLayer<highestLayer) {
			JInternalFrame[] frames = desktopPane.getAllFramesInLayer(highestLayer);
			desktopPane.setSelectedFrame(frames[0]);
			try {
				internalFrame.setSelected(false);
			}
			catch (java.beans.PropertyVetoException ex)
			{
				// no big deal if we can't deselect it
			}
		}
		
		String windowName=internalFrame.getName();
		//System.out.println("Window "+windowName+" got activated");
		if (windowName.equals(UIConstants.TITLE_MANIFEST_ENTRY)) {
			ManifestEntryFrame frame=(ManifestEntryFrame)internalFrame;
			AllContainersTable tableModel=(AllContainersTable)frame.containerListTable.getModel();
			tableModel.updateJobNum(frame.jobTextField.getText());
			tableModel.refresh();
			// calculate the totals
			int totalsRows=tableModel.getRowCount();
			float runningTotal=0;
			NumberFormat numFormat=new DecimalFormat(UIConstants.PATTERN_DEC_FORMAT_2);
			for (int count=0;count<totalsRows;count++) {
				Object obj=tableModel.getValueAt(count,AllContainersTable.FOB_AMOUNT);
				try {
					Number toAdd=numFormat.parse(obj.toString());
					if (obj!=null) {
						//runningTotal=runningTotal+new Float(obj.toString()).floatValue();
						runningTotal=runningTotal+toAdd.floatValue();
					}
				}
				catch (java.text.ParseException ex) {
					ex.printStackTrace(System.err);
				}
			}

			Float subTotalFloat=new Float(runningTotal);
			frame.subTotalTextField.setText(numFormat.format(subTotalFloat.doubleValue())  );
			float grandTotal=runningTotal;
			if (frame.freightTextField.getText().trim().length()>0) {
				try {
					grandTotal=runningTotal+
						numFormat.parse(frame.freightTextField.getText()).floatValue()+
						numFormat.parse(frame.truckingTextField.getText()).floatValue()+
						numFormat.parse(frame.miscTextField.getText()).floatValue();
//					grandTotal=runningTotal+new Float(frame.freightTextField.getText()).floatValue();
				}
				catch (NumberFormatException ex) {
					System.err.println("Ignoring the non numeric charge");
				}
				catch (java.text.ParseException ex) {
					ex.printStackTrace(System.err);
				}
			}
			Float grandTotalFloat=new Float(grandTotal);
			frame.grandTotalTextField.setText(numFormat.format(grandTotalFloat.doubleValue()));
			frame.containerListTable.revalidate();
			frame.containerListTable.repaint();
		}
		else if (windowName.equals(UIConstants.TITLE_MANIFESTS)) {
			//System.out.println("Refreshing main manifest frame");
			ManifestsFrame frame=(ManifestsFrame)internalFrame;
			AllManifestsTable tableModel=(AllManifestsTable)frame.manifestTable.getModel();
			tableModel.refresh();
			frame.newComboBox.setSelectedIndex(0);
			frame.manifestTable.revalidate();
			frame.manifestTable.repaint();
		}
		else if (windowName.equals(UIConstants.TITLE_JOBS)) {
			//System.out.println("Refreshing main jobs frame");
			JobsFrame frame=(JobsFrame)internalFrame;
			AllJobsTable tableModel=(AllJobsTable)frame.jobTable.getModel();
			tableModel.refresh();
			frame.jobTable.revalidate();
			frame.jobTable.repaint();
		}
		else if (windowName.equals(UIConstants.TITLE_CONTAINER_ENTRY)) {
			try {				
				ContainerEntryFrame mainFrame = (ContainerEntryFrame)internalFrame;
				ContactsDropDownListener dropDownListener = new ContactsDropDownListener();
				dropDownListener.setContainerEntryFrame(mainFrame);
				dropDownListener.setContactDAO(contactDAO);
				//ContactsDropDownListener dropDownListener = (ContactsDropDownListener)mainFrame.salesRepComboBox.getActionListeners()[0];
				long begin = System.currentTimeMillis();
				// populate suppliers
				ContactBean supplier = new ContactBean();
				supplier.setDepartment(UIConstants.DROPDOWN_METALS_SUPPLIER);
				List supplierList = contactDAO.findContacts(supplier);
				dropDownListener.setSupplierList(supplierList);
				String[] supplierStrings = new String[supplierList.size()];
				for (int count=0;count<supplierList.size();count++) {
					supplier = (ContactBean)supplierList.get(count);
					supplierStrings[count]=supplier.getCn();
				}
				Arrays.sort(supplierStrings);				
				// end dropdown populations
				long end = System.currentTimeMillis();
				System.out.println("Time to retrieve metals suppliers: "+(double)(end-begin)/1000);				
				// create dropdowns
								
				DefaultComboBoxModel suppliers = new DefaultComboBoxModel(supplierStrings);
				mainFrame.supplierNameComboBox.setName(UIConstants.DROPDOWN_METALS_SUPPLIER);
				mainFrame.supplierNameComboBox.addActionListener(dropDownListener);				
				mainFrame.supplierNameComboBox.setModel(suppliers);
				if (mainFrame.selectedSupplier!=null) {
					mainFrame.supplierNameComboBox.setSelectedItem(mainFrame.selectedSupplier);
				}

			}
			catch (DataAccessException ex) {
				System.err.println("Cannot populate the drop downs because: "+ex.getMessage());
			}
		
		}		
		else if (windowName.equals(UIConstants.TITLE_JOB_ENTRY)) {
			try {				
				JobEntryFrame mainFrame = (JobEntryFrame)internalFrame;
				ContactsDropDownListener dropDownListener = new ContactsDropDownListener();
				dropDownListener.setJobEntryFrame(mainFrame);
				dropDownListener.setContactDAO(contactDAO);
				//ContactsDropDownListener dropDownListener = (ContactsDropDownListener)mainFrame.salesRepComboBox.getActionListeners()[0];
				long begin = System.currentTimeMillis();
				
				// populate builder				
				ContactBean builder = new ContactBean();				
				builder.setDepartment(UIConstants.DROPDOWN_BUILDER);
				List builderList = contactDAO.findContacts(builder);
				dropDownListener.setRegSalesManList(builderList);
				String[] builderStrings = new String[builderList.size()+1];
				for (int count=0;count<builderList.size();count++) {
					builder = (ContactBean)builderList.get(count);
					builderStrings[count]=builder.getCn();
				}
				builderStrings[builderList.size()] = NA_STRING;
				Arrays.sort(builderStrings);
				
				// populate regional salesmanager				
				ContactBean regSalesMan = new ContactBean();				
				regSalesMan.setDepartment(UIConstants.DROPDOWN_REG_SALES_MAN);
				List regSalesManList = contactDAO.findContacts(regSalesMan);
				dropDownListener.setRegSalesManList(regSalesManList);
				String[] regSalesManStrings = new String[regSalesManList.size()];				
				for (int count=0;count<regSalesManList.size();count++) {
					regSalesMan = (ContactBean)regSalesManList.get(count);
					regSalesManStrings[count]=regSalesMan.getCn();
				}
				Arrays.sort(regSalesManStrings);
				
				// populate sales rep
				ContactBean salesRep = new ContactBean();
				salesRep.setDepartment(UIConstants.DROPDOWN_SALESREP);
				List salesRepList = contactDAO.findContacts(salesRep);
				dropDownListener.setSalesRepList(salesRepList);
				String[] salesRepStrings = new String[salesRepList.size()];				
				for (int count=0;count<salesRepList.size();count++) {
					salesRep = (ContactBean)salesRepList.get(count);
					salesRepStrings[count]=salesRep.getCn();
				}
				Arrays.sort(salesRepStrings);
				// populate suppliers
				ContactBean supplier = new ContactBean();
				supplier.setDepartment(UIConstants.DROPDOWN_SUPPLIER);
				List supplierList = contactDAO.findContacts(supplier);
				dropDownListener.setSupplierList(supplierList);
				String[] supplierStrings = new String[supplierList.size()];
				for (int count=0;count<supplierList.size();count++) {
					supplier = (ContactBean)supplierList.get(count);
					supplierStrings[count]=supplier.getCn();
				}
				Arrays.sort(supplierStrings);
				// populate contractors
				ContactBean contractor = new ContactBean();
				contractor.setDepartment(UIConstants.DROPDOWN_CONTRACTOR);
				List contractorList = contactDAO.findContacts(contractor);
				dropDownListener.setContractorList(contractorList);
				String[] contractorStrings = new String[contractorList.size()+1];				
				for (int count=0;count<contractorList.size();count++) {
					contractor = (ContactBean)contractorList.get(count);
					//System.out.println("loading "+contractor.getCn());
					contractorStrings[count]=contractor.getCn();
				}
				contractorStrings[contractorList.size()] = NA_STRING;
				Arrays.sort(contractorStrings);
				// end dropdown populations
				long end = System.currentTimeMillis();
				System.out.println("Time to retrieve job entry dropdowns: "+(double)(end-begin)/1000);
				
				// create dropdowns
				
				DefaultComboBoxModel regSalesMans = new DefaultComboBoxModel(regSalesManStrings);
				mainFrame.regSalesManComboBox.setName(UIConstants.DROPDOWN_REG_SALES_MAN);
				mainFrame.regSalesManComboBox.addActionListener(dropDownListener);
				mainFrame.regSalesManComboBox.setModel(regSalesMans);
				if (mainFrame.selectedRegSalesMan!=null) {
					mainFrame.regSalesManComboBox.setSelectedItem(mainFrame.selectedRegSalesMan);
				}
				
				DefaultComboBoxModel salesReps = new DefaultComboBoxModel(salesRepStrings);
				mainFrame.salesRepComboBox.setName(UIConstants.DROPDOWN_SALESREP);
				mainFrame.salesRepComboBox.addActionListener(dropDownListener);
				mainFrame.salesRepComboBox.setModel(salesReps);
				if (mainFrame.selectedSalesRep!=null) {
					mainFrame.salesRepComboBox.setSelectedItem(mainFrame.selectedSalesRep);
				}
				
				DefaultComboBoxModel builders = new DefaultComboBoxModel(builderStrings);
				mainFrame.builderNameComboBox.setName(UIConstants.DROPDOWN_BUILDER);
				mainFrame.builderNameComboBox.addActionListener(dropDownListener);
				mainFrame.builderNameComboBox.setModel(builders);
				if (mainFrame.selectedSalesRep!=null) {
					mainFrame.builderNameComboBox.setSelectedItem(mainFrame.selectedBuilder);
				}
				
				DefaultComboBoxModel suppliers = new DefaultComboBoxModel(supplierStrings);
				mainFrame.supplierNameComboBox.setName(UIConstants.DROPDOWN_SUPPLIER);
				mainFrame.supplierNameComboBox.addActionListener(dropDownListener);				
				mainFrame.supplierNameComboBox.setModel(suppliers);
				if (mainFrame.selectedSupplier!=null) {
					mainFrame.supplierNameComboBox.setSelectedItem(mainFrame.selectedSupplier);
				}
				DefaultComboBoxModel contractors = new DefaultComboBoxModel(contractorStrings);
				mainFrame.contractorNameComboBox.setName(UIConstants.DROPDOWN_CONTRACTOR);
				mainFrame.contractorNameComboBox.addActionListener(dropDownListener);
				mainFrame.contractorNameComboBox.setModel(contractors);	
				if (mainFrame.selectedContractor!=null) {
					mainFrame.contractorNameComboBox.setSelectedItem(mainFrame.selectedContractor);
				}
			}
			catch (DataAccessException ex) {
				System.err.println("Cannot populate the drop downs because: "+ex.getMessage());
			}
		}
			
	}
	
	public void actionPerformed(ActionEvent e) {
    String actionCommand=e.getActionCommand();
    Object queryObj=e.getSource();	

    if (actionCommand.equals(UIConstants.COMMAND_OPEN_METALS_CONTACTEDITOR)||actionCommand.equals(UIConstants.COMMAND_OPEN_JOBS_CONTACTEDITOR)) {
		JInternalFrame[] frames = desktopPane.getAllFramesInLayer(desktopPane.highestLayer());
		try {
				frames[0].setSelected(false);
			}
			catch (java.beans.PropertyVetoException ex)
			{
				// no big deal if we can't deselect it
			}
		//System.out.println("Selecting a new frame in open contact editor "+frames.length);
		
	}
	
  }

}
